using System;
using System.Collections.Generic;
using Volo.Abp.Domain.Entities.Auditing;

namespace CKY.AgentPlatform.PromptTemplates;

/// <summary>
/// 提示词模板类型枚举
/// </summary>
public enum PromptTemplateType
{
    /// <summary>
    /// 系统提示词
    /// </summary>
    SystemPrompt = 0,

    /// <summary>
    /// 用户提示词
    /// </summary>
    UserPrompt = 1,

    /// <summary>
    /// 对话模板
    /// </summary>
    ConversationTemplate = 2,

    /// <summary>
    /// 任务模板
    /// </summary>
    TaskTemplate = 3,

    /// <summary>
    /// 自定义模板
    /// </summary>
    CustomTemplate = 4,

    /// <summary>
    /// 简单文本
    /// </summary>
    SimpleText = 5,

    /// <summary>
    /// Mustache模板
    /// </summary>
    Mustache = 6,

    /// <summary>
    /// Liquid模板
    /// </summary>
    Liquid = 7,

    /// <summary>
    /// Handlebars模板
    /// </summary>
    Handlebars = 8,

    /// <summary>
    /// JavaScript模板
    /// </summary>
    JavaScript = 9
}

/// <summary>
/// 模板分类枚举
/// </summary>
public enum TemplateCategory
{
    /// <summary>
    /// 通用对话
    /// </summary>
    General = 0,
    
    /// <summary>
    /// 代码生成
    /// </summary>
    CodeGeneration = 1,
    
    /// <summary>
    /// 文本创作
    /// </summary>
    ContentCreation = 2,
    
    /// <summary>
    /// 数据分析
    /// </summary>
    DataAnalysis = 3,
    
    /// <summary>
    /// 翻译
    /// </summary>
    Translation = 4,
    
    /// <summary>
    /// 摘要总结
    /// </summary>
    Summarization = 5,
    
    /// <summary>
    /// 问答系统
    /// </summary>
    QnA = 6,
    
    /// <summary>
    /// 客服支持
    /// </summary>
    CustomerSupport = 7,
    
    /// <summary>
    /// 教育培训
    /// </summary>
    Education = 8,
    
    /// <summary>
    /// 自定义
    /// </summary>
    Custom = 99
}

/// <summary>
/// 提示词模板实体 - 管理和复用提示词模板
/// </summary>
public class PromptTemplate : AuditedAggregateRoot<Guid>
{
    /// <summary>
    /// 模板名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 模板描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 模板内容
    /// </summary>
    public string Template { get; set; }

    /// <summary>
    /// 模板内容（别名，向后兼容）
    /// </summary>
    public string TemplateContent
    {
        get => Template;
        set => Template = value;
    }

    /// <summary>
    /// 模板分类
    /// </summary>
    public TemplateCategory Category { get; set; }

    /// <summary>
    /// 模板类型
    /// </summary>
    public PromptTemplateType TemplateType { get; set; }

    /// <summary>
    /// 是否为系统模板
    /// </summary>
    public bool IsSystem { get; set; }

    /// <summary>
    /// 版本号
    /// </summary>
    public int Version { get; set; }

    /// <summary>
    /// 是否激活
    /// </summary>
    public bool IsActive { get; set; }

    /// <summary>
    /// 标签
    /// </summary>
    public string Tags { get; set; }

    /// <summary>
    /// 参数定义（JSON格式）
    /// </summary>
    public string Parameters { get; set; }

    /// <summary>
    /// 使用示例（JSON格式）
    /// </summary>
    public string Examples { get; set; }

    /// <summary>
    /// 使用次数统计
    /// </summary>
    public int UsageCount { get; set; }

    /// <summary>
    /// 父模板ID（用于模板继承）
    /// </summary>
    public Guid? ParentTemplateId { get; set; }

    /// <summary>
    /// 排序权重
    /// </summary>
    public int SortOrder { get; set; }

    /// <summary>
    /// 元数据（JSON格式）
    /// </summary>
    public string Metadata { get; set; }

    /// <summary>
    /// 最大长度
    /// </summary>
    public int MaxLength { get; set; }

    /// <summary>
    /// 后处理脚本
    /// </summary>
    public string PostProcessingScript { get; set; }

    /// <summary>
    /// 父模板
    /// </summary>
    public virtual PromptTemplate ParentTemplate { get; set; }

    /// <summary>
    /// 子模板列表
    /// </summary>
    public virtual ICollection<PromptTemplate> ChildTemplates { get; set; }

    protected PromptTemplate()
    {
        // EF Core requires parameterless constructor
        ChildTemplates = new HashSet<PromptTemplate>();
    }

    /// <summary>
    /// 创建新的提示词模板实例
    /// </summary>
    /// <param name="id">模板ID</param>
    /// <param name="name">模板名称</param>
    /// <param name="description">模板描述</param>
    /// <param name="template">模板内容</param>
    /// <param name="category">模板分类</param>
    public PromptTemplate(
        Guid id,
        string name,
        string description,
        string template,
        TemplateCategory category) : base(id)
    {
        Name = name;
        Description = description;
        Template = template;
        Category = category;
        IsSystem = false;
        Version = 1;
        IsActive = true;
        Tags = "";
        Parameters = "[]";
        Examples = "[]";
        UsageCount = 0;
        ParentTemplateId = null;
        SortOrder = 0;
        Metadata = "{}";
        MaxLength = 4000;
        PostProcessingScript = "";
        ChildTemplates = new HashSet<PromptTemplate>();
    }

    /// <summary>
    /// 渲染模板
    /// </summary>
    /// <param name="parameters">参数字典</param>
    /// <returns>渲染后的提示词</returns>
    public string RenderTemplate(Dictionary<string, object> parameters)
    {
        if (string.IsNullOrWhiteSpace(Template))
            return "";

        var result = Template;
        
        // 替换参数占位符 {{parameter_name}}
        foreach (var param in parameters)
        {
            var placeholder = $"{{{{{param.Key}}}}}";
            result = result.Replace(placeholder, param.Value?.ToString() ?? "");
        }

        // 如果有父模板，先渲染父模板
        if (ParentTemplate != null)
        {
            var parentResult = ParentTemplate.RenderTemplate(parameters);
            result = parentResult + "\n" + result;
        }

        return result.Trim();
    }

    /// <summary>
    /// 获取模板参数列表
    /// </summary>
    /// <returns>参数列表</returns>
    public List<TemplateParameter> GetParameters()
    {
        try
        {
            if (string.IsNullOrWhiteSpace(Parameters))
                return new List<TemplateParameter>();

            return System.Text.Json.JsonSerializer.Deserialize<List<TemplateParameter>>(Parameters) 
                   ?? new List<TemplateParameter>();
        }
        catch
        {
            return new List<TemplateParameter>();
        }
    }

    /// <summary>
    /// 验证必需参数
    /// </summary>
    /// <param name="parameters">提供的参数</param>
    /// <returns>验证结果</returns>
    public (bool isValid, List<string> missingParams) ValidateParameters(Dictionary<string, object> parameters)
    {
        var templateParams = GetParameters();
        var missingParams = new List<string>();

        foreach (var param in templateParams.Where(p => p.IsRequired))
        {
            if (!parameters.ContainsKey(param.Name) || parameters[param.Name] == null)
            {
                missingParams.Add(param.Name);
            }
        }

        return (missingParams.Count == 0, missingParams);
    }

    /// <summary>
    /// 增加使用次数
    /// </summary>
    public void IncrementUsage()
    {
        UsageCount++;
    }

    /// <summary>
    /// 创建新版本
    /// </summary>
    /// <param name="newTemplateContent">新的模板内容</param>
    /// <returns>新版本的模板</returns>
    public PromptTemplate CreateNewVersion(string newTemplateContent)
    {
        var newTemplate = new PromptTemplate(
            Guid.NewGuid(),
            $"{Name} (v{Version + 1})",
            Description,
            newTemplateContent,
            Category)
        {
            IsSystem = IsSystem,
            Version = Version + 1,
            IsActive = true,
            Tags = Tags,
            Parameters = Parameters,
            Examples = Examples,
            ParentTemplateId = ParentTemplateId,
            SortOrder = SortOrder,
            Metadata = Metadata
        };

        return newTemplate;
    }

    /// <summary>
    /// 克隆模板
    /// </summary>
    /// <param name="newName">新名称</param>
    /// <returns>克隆的模板</returns>
    public PromptTemplate Clone(string newName)
    {
        var clonedTemplate = new PromptTemplate(
            Guid.NewGuid(),
            newName,
            Description,
            Template,
            Category)
        {
            IsSystem = false,
            Version = 1,
            IsActive = true,
            Tags = Tags,
            Parameters = Parameters,
            Examples = Examples,
            ParentTemplateId = ParentTemplateId,
            SortOrder = SortOrder,
            Metadata = Metadata
        };

        return clonedTemplate;
    }

    /// <summary>
    /// 更新标签
    /// </summary>
    /// <param name="tags">标签字符串，逗号分隔</param>
    public void UpdateTags(string tags)
    {
        Tags = tags ?? "";
    }

    /// <summary>
    /// 检查模板是否有效
    /// </summary>
    /// <returns>是否有效</returns>
    public bool IsValid()
    {
        return !string.IsNullOrWhiteSpace(Name) &&
               !string.IsNullOrWhiteSpace(Template) &&
               !string.IsNullOrWhiteSpace(Description);
    }

    /// <summary>
    /// 获取模板预览（前100个字符）
    /// </summary>
    /// <returns>预览内容</returns>
    public string GetPreview()
    {
        if (string.IsNullOrWhiteSpace(Template))
            return "";

        return Template.Length > 100
            ? Template.Substring(0, 100) + "..."
            : Template;
    }

    /// <summary>
    /// 设置模板名称
    /// </summary>
    /// <param name="name">新名称</param>
    public void SetName(string name)
    {
        Name = name ?? "";
    }

    /// <summary>
    /// 设置模板描述
    /// </summary>
    /// <param name="description">新描述</param>
    public void SetDescription(string description)
    {
        Description = description ?? "";
    }

    /// <summary>
    /// 设置模板内容
    /// </summary>
    /// <param name="content">新内容</param>
    public void SetContent(string content)
    {
        Template = content ?? "";
    }

    /// <summary>
    /// 设置版本号
    /// </summary>
    /// <param name="version">版本号</param>
    public void SetVersion(string version)
    {
        // 尝试解析版本号，如果失败则使用默认值1
        if (int.TryParse(version, out int versionNumber))
        {
            Version = versionNumber;
        }
        else
        {
            Version = 1;
        }
    }

    /// <summary>
    /// 设置父模板ID
    /// </summary>
    /// <param name="parentTemplateId">父模板ID</param>
    public void SetParentTemplateId(Guid? parentTemplateId)
    {
        ParentTemplateId = parentTemplateId;
    }
}

/// <summary>
/// 提示词模板参数定义
/// </summary>
public class PromptTemplateParameter
{
    /// <summary>
    /// 参数名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 参数描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 是否必需
    /// </summary>
    public bool IsRequired { get; set; }

    /// <summary>
    /// 参数类型
    /// </summary>
    public string Type { get; set; }

    /// <summary>
    /// 默认值
    /// </summary>
    public object DefaultValue { get; set; }

    /// <summary>
    /// 参数选项（用于枚举类型）
    /// </summary>
    public List<string> Options { get; set; }

    public PromptTemplateParameter()
    {
        Options = new List<string>();
    }
}

/// <summary>
/// 模板参数定义（向后兼容）
/// </summary>
public class TemplateParameter : PromptTemplateParameter
{
    /// <summary>
    /// 参数名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 参数描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 是否必需
    /// </summary>
    public bool IsRequired { get; set; }

    /// <summary>
    /// 参数类型
    /// </summary>
    public string Type { get; set; }

    /// <summary>
    /// 默认值
    /// </summary>
    public object DefaultValue { get; set; }

    /// <summary>
    /// 参数选项（用于枚举类型）
    /// </summary>
    public List<string> Options { get; set; }

    public TemplateParameter()
    {
        Options = new List<string>();
    }
}

/// <summary>
/// 提示词模板处理结果
/// </summary>
public class PromptTemplateResult
{
    /// <summary>
    /// 是否成功
    /// </summary>
    public bool IsSuccess { get; set; }

    /// <summary>
    /// 处理后的提示词
    /// </summary>
    public string ProcessedPrompt { get; set; } = string.Empty;

    /// <summary>
    /// 错误信息
    /// </summary>
    public string ErrorMessage { get; set; } = string.Empty;

    /// <summary>
    /// 使用的参数
    /// </summary>
    public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();

    /// <summary>
    /// 处理时间
    /// </summary>
    public DateTime ProcessedAt { get; set; } = DateTime.UtcNow;

    public PromptTemplateResult()
    {
        IsSuccess = true;
    }
}